package com.softserve.crazymachine.communicator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleHttpServer {
	private ServerSocket serverSocket;

	/*
	 * @param port The TCP port to begin listening on.
	 * 
	 * @throws IOException Thrown if any sort of error occurs.
	 */

	public SimpleHttpServer(int port) throws IOException {

		serverSocket = new ServerSocket(port);

	}

	public void run() {
		try {
			while (!serverSocket.isClosed()) {
				Socket clientSocket = serverSocket.accept();
				handleClientSession(clientSocket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println("Server stopped. Terminating");
		}
	}

	private void stop() {
		try {
			serverSocket.close();
			System.out.println("Server has been stoped");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void restart(int port) throws IOException {
		stop();
		serverSocket = new ServerSocket(port);
		System.out.println("Server started");
	}

	private void handleClientSession(Socket socket) throws IOException {
		// Read socket data

		InputStream is = socket.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		// Write socket data
		java.io.OutputStream os = socket.getOutputStream();
		PrintStream out = new PrintStream(os);

		// read in first line

		System.out.println("***New Request***");
		String first = br.readLine();
		System.out.println(first);

		// read header

		String line;
		do {
			line = br.readLine();
			if (line != null)
				;
			System.out.println(line);
		} while (line != null && line.trim().length() > 0);

		// write the HTTP response
		out.println("HTTP/1.1 200 OK");
		out.println("");
		out.println("<html>");
		out.println("<head><TITLE>Simple Web Server</TITLE></head>");
		out.println("<body>");
		out.println("<h1>Hello WORLD</h1>");
		out.println("</body>");
		out.println("</html>");

		// Close everything up
		out.close();
		br.close();
		socket.close();
		this.restart(8081);
	}

	public static void main(String args[]) {

		try {
			if (args.length < 1) {
				System.err.println("Usage:\njava SimpleWebServer [port]");
			} else {
				int port;
				try {
					port = Integer.parseInt(args[0]);
					SimpleHttpServer server = new SimpleHttpServer(port);
					server.run();
				} catch (NumberFormatException e) {
					System.out.println("Invalid port number");

				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
